﻿using Common.DictComponent;
using DAL;
using IService;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Service
{
    public class DictService:IDictService
    {
        private readonly IDictRepository _dictRepository;
        // 依赖抽象 IRedisDictCacheService，而非主项目 RedisDictCacheService
        private readonly IRedisDictCacheService _redisCacheService;

        public DictService(IDictRepository dictRepository, IRedisDictCacheService redisCacheService)
        {
            _dictRepository = dictRepository;
            _redisCacheService = redisCacheService;
        }

        public async Task<WmsDictType> GetDictTypeAsync(string code)
        {
            // 先查 Redis
            var cacheResult = await _redisCacheService.GetDictTypeAsync(code);
            if (cacheResult != null) return cacheResult;

            // Redis 没有，查数据库
            var dbResult = await _dictRepository.GetDictTypeByCodeAsync(code);
            if (dbResult != null)
            {
                // 数据库查到后，写入 Redis
                await _redisCacheService.SetDictTypeAsync(dbResult);
            }
            return dbResult;
        }

        public async Task<List<WmsDictData>> GetDictDataListAsync(long typeId)
        {
            // 先查 Redis
            var cacheResult = await _redisCacheService.GetDictDataListAsync(typeId);
            if (cacheResult.Any()) return cacheResult;

            // Redis 没有，查数据库
            var dbResult = await _dictRepository.GetDictDataByTypeIdAsync(typeId);
            if (dbResult != null && dbResult.Any())
            {
                // 数据库查到后，写入 Redis
                await _redisCacheService.SetDictDataListAsync(typeId, dbResult);
            }
            return dbResult;
        }

        public async Task UpdateDictTypeAsync(WmsDictType dictType)
        {
            // 更新数据库
            await _dictRepository.UpdateDictTypeAsync(dictType);
            // 清除 Redis 缓存（保证下次读取最新数据）
            await _redisCacheService.ClearDictTypeCacheAsync(dictType.Code);
        }

        public async Task UpdateDictDataAsync(WmsDictData dictData)
        {
            // 更新数据库
            await _dictRepository.UpdateDictDataAsync(dictData);
            // 清除 Redis 缓存（保证下次读取最新数据）
            await _redisCacheService.ClearDictDataCacheAsync(dictData.DictTypeId);
        }
    }
}
